package com.imedway.ihe.dtz.xds.util;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;

import org.openehealth.ipf.commons.ihe.xds.core.ebxml.ebxml30.ProvideAndRegisterDocumentSetRequestType;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import lombok.extern.slf4j.Slf4j;


/**
 * 使用Jaxb2.0实现XML<->Java Object的Mapper.
 * <p>
 * 在创建时需要设定所有需要序列化的Root对象的Class.
 * 特别支持Root对象是Collection的情形.
 *
 * @author calvin
 * @version 2013-01-15
 */
@Slf4j
@SuppressWarnings("rawtypes")
public class JaxbMapperUtils {

    private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();

//    /**
//     * Java Object->Xml without encoding.
//     */
//    public static String toXml(Object root) {
//        Class clazz = Reflections.getUserClass(root);
//        return toXml(root, clazz, null);
//    }
//
//    /**
//     * Java Object->Xml with encoding.
//     */
//    public static String toXml(Object root, String encoding) {
//        Class clazz = Reflections.getUserClass(root);
//        return toXml(root, clazz, encoding);
//    }

    /**
     * Java Object->Xml with encoding.
     */
    public static String toXml(Object root, Class clazz, String encoding) {
        try {
            StringWriter writer = new StringWriter();
            createMarshaller(clazz, encoding).marshal(root, writer);
            return writer.toString();
        } catch (JAXBException e) {
        	return encoding;
        }
		
    }

    public static String toXml(Object body)  {
        JAXBContext context;
        StringWriter writer = new StringWriter();
		try {
			context = JAXBContext.newInstance(body.getClass());
	        Marshaller marshaller = context.createMarshaller();
	        Unmarshaller unmarshaller = context.createUnmarshaller();

	        marshaller.marshal(unmarshaller, writer);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return writer.toString();
    }
	

//    /**
//     * Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
//     */
//    public static String toXml(Collection<?> root, String rootName, Class clazz) {
//        return toXml(root, rootName, clazz, null);
//    }

//    /**
//     * Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
//     */
//    public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
//        try {
//            CollectionWrapper wrapper = new CollectionWrapper();
//            wrapper.collection = root;
//
//            JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
//                    CollectionWrapper.class, wrapper);
//
//            StringWriter writer = new StringWriter();
//            createMarshaller(clazz, encoding).marshal(wrapperElement, writer);
//
//            return writer.toString();
//        } catch (JAXBException e) {
//            throw Exceptions.unchecked(e);
//        }
//    }

//    /**
//     * Xml->Java Object.
//     */
//    @SuppressWarnings("unchecked")
//    public static <T> T fromXml(String xml, Class<T> clazz) {
//        try {
//            StringReader reader = new StringReader(xml);
//            return (T) createUnmarshaller(clazz).unmarshal(reader);
//        } catch (JAXBException e) {
//            throw Exceptions.unchecked(e);
//        }
//    }

    /**
     * 创建Marshaller并设定encoding(可为null).
     * 线程不安全，需要每次创建或pooling。
     */
    public static Marshaller createMarshaller(Class clazz, String encoding) {
        try {
            JAXBContext jaxbContext = getJaxbContext(clazz);
            
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
            if (StringUtils.hasText(encoding)) {
                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            }

            return marshaller;
        } catch (JAXBException e) {
    		e.printStackTrace();
    		 return null;
        }

    }
    public static Unmarshaller createUmMarshaller(Class clazz, String encoding) {
        try {
            JAXBContext jaxbContext = getJaxbContext(clazz);
            
            Unmarshaller marshaller = jaxbContext.createUnmarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            
            if (StringUtils.hasText(encoding)) {
                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            }

            return marshaller;
        } catch (JAXBException e) {
    		e.printStackTrace();
    		 return null;
        }

    }
    public static String toXmlMtom(ProvideAndRegisterDocumentSetRequestType body) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(body.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setAttachmentMarshaller(new org.openehealth.ipf.commons.ihe.ws.cxf.NonReadingAttachmentMarshaller());
            marshaller.setListener(new org.openehealth.ipf.commons.ihe.xds.core.XdsJaxbDataBinding.MarshallerListener());
            marshaller.setProperty("jaxb.formatted.output", true);
            StringWriter writer = new StringWriter();
            marshaller.marshal(body, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
		return result;
	}
    /**
     * 创建UnMarshaller.
     * 线程不安全，需要每次创建或pooling。
     */
    public static Unmarshaller createUnmarshaller(Class clazz) {
        try {
            JAXBContext jaxbContext = getJaxbContext(clazz);
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
        	e.printStackTrace();
   		   return null;
        }
    }

    protected static JAXBContext getJaxbContext(Class clazz) {
        Assert.notNull(clazz, "'clazz' must not be null");
        JAXBContext jaxbContext = jaxbContexts.get(clazz);
        if (jaxbContext == null) {
            try {
                jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
                jaxbContexts.putIfAbsent(clazz, jaxbContext);
            } catch (JAXBException ex) {
                throw new HttpMessageConversionException("Could not instantiate JAXBContext for class [" + clazz
                        + "]: " + ex.getMessage(), ex);
            }
        }
        return jaxbContext;
    }

    /**
     * 封装Root Element 是 Collection的情况.
     */
    public static class CollectionWrapper {

        @XmlAnyElement
        protected Collection<?> collection;
    }
    /**
     * JavaBean转换成xml
     * 
     * @param obj
     * @param encoding
     * @return
     */
    public static String convertToXml(Object obj, String encoding, boolean format) {
        String result = null;
        StringWriter writer = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
